import { db } from './DexieDB'

interface FetchOptions extends RequestInit {
    timeout?: number;
    baseUrl?: string;
}
// 基础配置
let DEFAULT_BASE_URL: string, DEFAULT_TIMEOUT: number


async function initializeConfig() {
    const device = await db.device.get(1)
    DEFAULT_BASE_URL = device!.baseUrl;
    DEFAULT_TIMEOUT = device!.timeout;
}
// 基础 fetch 封装
async function customFetch(url: string, options: FetchOptions = {}): Promise<Response> {

    await initializeConfig();
    const { timeout = DEFAULT_TIMEOUT, baseUrl = DEFAULT_BASE_URL, ...fetchOptions } = options;

    // console.log('url', url);
    // console.log('fullUrl', baseUrl);

    console.log('baseUrl', baseUrl);

    // 处理完整的 URL - 修复路径拼接问题
    let fullUrl: string | URL = url;
    if (baseUrl) {
        // 如果 url 是绝对路径（以 / 开头），需要特殊处理保留 baseUrl 的路径
        if (url.startsWith('/')) {
            // 移除 baseUrl 末尾的斜杠，然后拼接 url
            const base = baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl;
            fullUrl = base + url;
        } else {
            // 相对路径的情况
            fullUrl = new URL(url, baseUrl);
        }
    }

    console.log('fullUrl', fullUrl);
    console.log('发送时间:', new Date().toLocaleString());

    // console.log('timeout', timeout, timeout * 1000 * 60, 'ms');

    // const fetchPromise = fetch(fullUrl, fetchOptions);

    // const timeoutPromise = new Promise<Response>((_, reject) => {
    //     setTimeout(() => {
    //         reject(new Error(`请求超时: ${fullUrl}`));
    //     }, timeout * 1000 * 60);
    // });

    // return Promise.race([fetchPromise, timeoutPromise]);
    // console.log('超时时间:', timeout);

    try {
        const controller = new AbortController();
        const { signal } = controller;

        const fetchOptionsWithSignal = {
            ...fetchOptions,
            signal
        };

        const fetchPromise = fetch(fullUrl, fetchOptionsWithSignal);

        const timeoutPromise = new Promise<Response>((_, reject) => {
            setTimeout(() => {
                controller.abort();
                reject(new Error(`请求超时: ${fullUrl}`));
            }, timeout * 1000 * 60);
        });

        return await Promise.race([fetchPromise, timeoutPromise]);
    } catch (error) {
        // // 请求失败时存储到重试任务表
        // await saveRetryTask(fullUrl.toString(), fetchOptions, error);
        // throw error; // 重新抛出错误供上层处理
        return Promise.reject({
            error, url, fetchOptions,
        });
    }
}

// GET 请求封装
export async function get<T = any>(url: string, params?: Record<string, any>, options?: Omit<FetchOptions, 'method' | 'body'>): Promise<T> {
    const queryString = params
        ? '?' + new URLSearchParams(params).toString()
        : '';

    const response = await customFetch(url + queryString, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            ...options?.headers
        },
        ...options
    });

    return response.json();
}

// POST 请求封装
export async function post<T = any>(url: string, data?: any, options?: Omit<FetchOptions, 'method' | 'body'>): Promise<T> {
    const response = await customFetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            ...options?.headers
        },
        body: JSON.stringify(data),
        ...options
    });

    return response.json();
}

// POST 请求封装（带查询参数）
export async function postWithQuery<T = any>(url: string, params?: Record<string, any>, data?: any, options?: Omit<FetchOptions, 'method' | 'body'>): Promise<T> {
    // 拼接查询参数
    let fullUrl = url;
    if (params) {
        const queryString = new URLSearchParams(params).toString();
        fullUrl = queryString ? `${url}?${queryString}` : url;
    }

    const response = await customFetch(fullUrl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            ...options?.headers
        },
        body: JSON.stringify(data),
        ...options
    });

    return response.json();
}

// 文件上传封装
export async function upload<T = any>(url: string, data: Record<string, string | Blob | File>, options?: Omit<FetchOptions, 'method' | 'body'>): Promise<T> {
    const response = await customFetch(url, {
        method: 'POST',
        body: createFormData(data),
        // 注意：上传文件时不要设置 Content-Type，让浏览器自动设置
        ...options
    });

    return response.json();
}

// FormData 创建辅助函数
export function createFormData(data: Record<string, string | Blob | File>): FormData {
    const formData = new FormData();

    Object.entries(data).forEach(([key, value]) => {
        formData.append(key, value);
    });

    return formData;
}

// 设置默认 baseUrl 的辅助函数
export function setDefaultBaseUrl(baseUrl: string): void {
    (DEFAULT_BASE_URL as string) = baseUrl;
}


export default customFetch;